package com.quyunshuo.module.home.view

import android.content.Context
import android.graphics.Color
import android.graphics.Shader
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.quyunshuo.module.home.R
import kotlin.math.cos
import kotlin.math.sin
import android.graphics.LinearGradient

/**
 * 渐变色文本
 */
class GradientTextView(context: Context, attrs: AttributeSet) : AppCompatTextView(context, attrs) {

    private var startColor = Color.RED
    private var endColor = Color.BLUE
    private var angle = 0

    init {
        context.obtainStyledAttributes(attrs, R.styleable.GradientTextView).apply {
            startColor = getColor(R.styleable.GradientTextView_startColor, Color.RED)
            endColor = getColor(R.styleable.GradientTextView_endColor, Color.BLUE)
            angle = getInt(R.styleable.GradientTextView_gradientAngle, 0)
            recycle()
        }
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        if (changed) {
            val radians = Math.toRadians(angle.toDouble())
            val x = (width * cos(radians)).toFloat()
            val y = (width * sin(radians)).toFloat()
            paint.shader = LinearGradient(
                0f, 0f, x, y,
                intArrayOf(startColor, endColor),
                null,
                Shader.TileMode.CLAMP
            )
        }
    }
}